package com.campus.activity.controller;

import com.campus.activity.common.Result;
import com.campus.activity.entity.User;
import com.campus.activity.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 用户管理控制器
 * 
 * @author System
 * @since 2024
 */
@RestController
@RequestMapping("/api/users")
@Tag(name = "用户管理", description = "用户登录注册和账户管理")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录验证")
    public Result<User> login(
            @RequestBody User  user) {
        User entity =  userService.login(user.getUsername(), user.getPassword());
        if (entity != null) {
            // 清除密码信息
            entity.setPassword(null);
            return Result.success("登录成功", entity);
        } else {
            return Result.error("用户名或密码错误");
        }
    }

    @PostMapping("/register")
    @Operation(summary = "用户注册", description = "新用户注册")
    public Result<Boolean> register(@Valid @RequestBody User user) {
        boolean success = userService.register(user);
        if (success) {
            return Result.success("注册成功", true);
        } else {
            return Result.error("注册失败，用户名可能已存在");
        }
    }

    @GetMapping("/username/{username}")
    @Operation(summary = "根据用户名查询用户", description = "根据用户名获取用户信息")
    public Result<User> getUserByUsername(
            @Parameter(description = "用户名") @PathVariable String username) {
        User user = userService.getUserByUsername(username);
        if (user != null) {
            user.setPassword(null); // 清除密码信息
            return Result.success(user);
        } else {
            return Result.notFound();
        }
    }

    @GetMapping("/role/{userRole}")
    @Operation(summary = "根据角色查询用户", description = "根据用户角色获取用户列表")
    public Result<List<User>> getUsersByRole(
            @Parameter(description = "用户角色") @PathVariable String userRole) {
        List<User> users = userService.getUsersByRole(userRole);
        // 清除密码信息
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }

    @PutMapping("/{userId}/password")
    @Operation(summary = "修改密码", description = "用户修改密码")
    public Result<Boolean> updatePassword(
            @Parameter(description = "用户ID") @PathVariable Integer userId,
            @Parameter(description = "旧密码") @RequestParam String oldPassword,
            @Parameter(description = "新密码") @RequestParam String newPassword) {
        boolean success = userService.updatePassword(userId, oldPassword, newPassword);
        return success ? Result.success("密码修改成功", true) : Result.error("密码修改失败，请检查旧密码");
    }

    @GetMapping("/student/{studentId}")
    @Operation(summary = "根据学生ID查询用户", description = "根据学生ID获取对应的用户信息")
    public Result<User> getUserByStudentId(
            @Parameter(description = "学生ID") @PathVariable Integer studentId) {
        User user = userService.getUserByStudentId(studentId);
        if (user != null) {
            user.setPassword(null); // 清除密码信息
            return Result.success(user);
        } else {
            return Result.notFound();
        }
    }

    @GetMapping("/organizer/{organizerId}")
    @Operation(summary = "根据组织者ID查询用户", description = "根据组织者ID获取对应的用户信息")
    public Result<User> getUserByOrganizerId(
            @Parameter(description = "组织者ID") @PathVariable Integer organizerId) {
        User user = userService.getUserByOrganizerId(organizerId);
        if (user != null) {
            user.setPassword(null); // 清除密码信息
            return Result.success(user);
        } else {
            return Result.notFound();
        }
    }

    @GetMapping("/check-username")
    @Operation(summary = "检查用户名", description = "检查用户名是否已存在")
    public Result<Boolean> checkUsername(
            @Parameter(description = "用户名") @RequestParam String username) {
        boolean exists = userService.isUsernameExists(username);
        return Result.success(exists);
    }

    @GetMapping("/{userId}")
    @Operation(summary = "获取用户详情", description = "根据用户ID获取用户详细信息")
    public Result<User> getUser(
            @Parameter(description = "用户ID") @PathVariable Integer userId) {
        User user = userService.getById(userId);
        if (user != null) {
            user.setPassword(null); // 清除密码信息
            return Result.success(user);
        } else {
            return Result.notFound();
        }
    }

    @PutMapping("/{userId}")
    @Operation(summary = "更新用户信息", description = "更新用户基本信息")
    public Result<Boolean> updateUser(
            @Parameter(description = "用户ID") @PathVariable Integer userId,
            @Valid @RequestBody User user) {
        user.setUserId(userId);
        // 不允许通过此接口修改密码
        user.setPassword(null);
        boolean success = userService.updateById(user);
        return success ? Result.success("用户信息更新成功", true) : Result.error("用户信息更新失败");
    }

    @DeleteMapping("/{userId}")
    @Operation(summary = "删除用户", description = "删除指定用户")
    public Result<Boolean> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Integer userId) {
        boolean success = userService.removeById(userId);
        return success ? Result.success("用户删除成功", true) : Result.error("用户删除失败");
    }
}